package com.example.ywj.myapplication.AsyncTask;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTask extends AsyncTask<Void,Integer,Bitmap> {
    private ProgressBar pb;
    private ImageView iv;
    public DownloadTask(ProgressBar pb,ImageView iv) {
        this.pb = pb;
        this.iv = iv;
    }
    /*
    * 开启任务之前执行
    * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        iv.setImageBitmap(bitmap);
        super.onPostExecute(bitmap);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        pb.setProgress(values[0]);
        super.onProgressUpdate(values);
    }

    /**
     * 执行耗时任务，运行在子线程中
     * @return
     */
    @Override
    protected Bitmap doInBackground(Void... voids) {
        Bitmap bitmap = null;
        try {
            // 1.创建URL对象
            URL url = new URL("http://10.11.71.87:8080/images/xiaoji.jpg");
            // 2.获得连接
            HttpURLConnection conn  = (HttpURLConnection) url.openConnection();
            // 3. 设置请求方式(如果不设置，默认get方式)
            conn.setRequestMethod("GET");
            // 4.设置超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            //  5.连接
            conn.connect();
            int responseCode =  conn.getResponseCode();
            // 返回200时，成功获取数据
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream is =  conn.getInputStream();
                // 将流转为bitmap对象   (  也可以将流is转为String)
                bitmap = BitmapFactory.decodeStream(is);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        int progress = 0;
        while (progress<100){
            progress += 5;
            try{
                Thread.sleep(500);
            }catch (Exception e){
                e.printStackTrace();
            }
            publishProgress(progress);
        }
        return bitmap;
    }
}
